package com.zs.toolbox.web2j.system.storage.service;

import com.aliyun.oss.OSSClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.InputStream;

/**
 * Copyright ©2016
 *
 * @author shuai.zhang  on 2017/6/2
 * @version 1.0.0
 * @description
 */
@Service
@Slf4j
@ConditionalOnProperty(prefix = "wt.storage.oss", name = "endpoint")
public class WtOssStorageServiceImpl implements WtStorageService {

	@Value("${wt.storage.oss.endpoint}")
	String endpoint;

	// 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
	@Value("${wt.storage.oss.accesskey.id}")
	String accessKeyId;

	@Value("${wt.storage.oss.accesskey.secret}")
	String accessKeySecret;

	@Value("${wt.storage.oss.bucket.name}")
	String bucketName;

	OSSClient ossClient;

	public WtOssStorageServiceImpl() {
		log.info("创建ALI OSS 存储器");

	}

	@PostConstruct
	void init() {
		ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
	}

	/*
        * oss-cn-beijing.aliyuncs.com
            zsstorage.oss-cn-beijing.aliyuncs.com
        * */
	// 创建OSSClient实例。

	@Override
	public String saveFile(String relativeFullFilePath, InputStream inputStream) {
		ossClient.putObject(bucketName,relativeFullFilePath, inputStream);
		return relativeFullFilePath;
	}

	@PreDestroy
	void deinit() {
		ossClient.shutdown();
	}
}
